//
//  uiLog.cpp
//  trail-map-editor
//
//  Created by Giorgio Tino on 3/6/13.
//
//
#include <time.h>
#include <stdarg.h>

#include "ui.h"
//--------------------------------------------------------------
//--------------------------------------------------------------
//- GLOBALS ----------------------------------------------------
//--------------------------------------------------------------
//--------------------------------------------------------------
uiLog Log;

bool uiLog::init( const char* szFilename )
{
	FILE*  pFile;
	time_t ttime;
	tm*    pCurTime;
	char   cLogStart[128];
	
	//Store filename & type for later use
	m_szFilename= szFilename;
	
	//Get the current time
	time( &ttime );
	pCurTime= localtime(&ttime);
	strftime( cLogStart, 128, "Log Started on %m/%d/%Y at %H:%M:%S", pCurTime );
	
	//open the log file
	pFile= fopen( szFilename, "wt" );
	
	//something *really* went wrong
	if( !pFile )
		return false;
	
	//setup the HTML file
	fprintf( pFile, "<HTML>\n<TITLE>%s</TITLE>\n"
			"<BODY BGCOLOR= 000000>\n"
			"<FONT COLOR= FFFFFF>%s</FONT><BR><BR>\n"
			"</BODY>\n</HTML>", cLogStart, cLogStart );
	
	//enable the log
	m_bEnabled= true;
	
	//close the log file
	fclose( pFile );
	return true;
}

void uiLog::write( eLogColors color, const char* szString, ... )
{
	FILE* pFile;
	va_list va;
	time_t ttime;
	tm* pCurTime;
	
	char szParsedString[1024];
	char szLogTime[32];
	
	if( !m_bEnabled )
		return;
	
	//get time
	time( &ttime );
	pCurTime= localtime( &ttime );
	strftime( szLogTime, 32, "<PRE>%H:%M:%S    ", pCurTime );
	
	//parse the given string
	va_start( va, szString );
	vsprintf( szParsedString, szString, va );
	va_end( va );
	
	//open the log file
	pFile= fopen( m_szFilename, "r+" );
	if( !pFile )
		return;
	
	//write text to the log file
	fseek( pFile, -16, SEEK_END );
	fprintf( pFile, "<FONT COLOR= \"%s\">%s %s</PRE></FONT>\n"
			"</BODY>\n</HTML>", getColor( color ), szLogTime, szParsedString );
	fclose( pFile );
}

const char* uiLog::getColor( eLogColors color ) const
{
	switch( color )
	{
		case Success:
			return "#00FF00";
			break;
            
        case Debug:
			return "#00FFFF";
			break;
            
        case Warning:
			return "#FFFF00";
			break;
            
        case Error:
			return "#FF0000";
			break;
			
		case Fatal:
			return "#FF00FF";
			break;
			
		case PlainText:
			return "#FFFFFF";
			break;
			
		case Renderer:
			return "#4995B1";
			break;
	}
	
	return NULL;
}
